package com.ruoyi.waybill.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.ruoyi.common.constant.WaybillConstants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.exitwarehouse.domain.WExitWarehouseInfo;
import com.ruoyi.exitwarehouse.service.IWExitWarehouseInfoService;
import com.ruoyi.goods.service.ITGoodsInfoService;
import com.ruoyi.system.domain.TNumberPersistenceInfo;
import com.ruoyi.system.service.ITNumberPersistenceInfoService;
import com.ruoyi.transport.service.ITTransportPlanService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.waybill.domain.TWayBillInfo;
import com.ruoyi.waybill.service.ITWayBillInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.domain.TSendReceiveInfo;
import com.ruoyi.system.service.ITSendReceiveInfoService;
import com.ruoyi.system.domain.TVehicleDriverInfo;
import com.ruoyi.system.service.ITVehicleDriverInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 运单信息Controller
 * 
 * @author wzy
 * @date 2024-12-31 19:09:03
 */
@RestController
@RequestMapping("/waybills/waybill")
public class TWayBillInfoController extends BaseController
{
    @Autowired
    private ITWayBillInfoService tWayBillInfoService;

    @Autowired
    private ITSendReceiveInfoService tSendReceiveInfoService;

    @Autowired
    private ITVehicleDriverInfoService tVehicleDriverInfoService;

    @Autowired
    private ITGoodsInfoService tGoodsInfoService;

    @Autowired
    private IWExitWarehouseInfoService wExitWarehouseInfoService;

    @Autowired
    private ITNumberPersistenceInfoService tNumberPersistenceInfoService;

    @Autowired
    private ITTransportPlanService tTransportPlanService;

    private static Logger logger = LoggerFactory.getLogger(TWayBillInfoController.class);

    /**
     * 查询运单信息列表
     */
    @PreAuthorize("@ss.hasAnyPermi('waybills:waybill:list, waybills:upwardwaybill:list, waybills:downwardwaybill:list, waybills:sign:list, waybills:query:list, waybills:account:list')")
    @GetMapping("/list")
    public TableDataInfo list(TWayBillInfo tWayBillInfo)
    {
        String bundleNumber = tWayBillInfo.getBundleNumber();
        if(StringUtils.isNotEmpty(bundleNumber)) {
            tWayBillInfo.setBundleNumber(bundleNumber.replace(",", "|"));
        }
        startPage();
        List<TWayBillInfo> list = tWayBillInfoService.selectTWayBillInfoList(tWayBillInfo);
        return getDataTable(list);
    }

    /**
     * 导出运单信息列表
     */
    @PreAuthorize("@ss.hasAnyPermi('waybills:waybill:export, waybills:upwardwaybill:export, waybills:downwardwaybill:export, waybills:sign:export, waybills:query:export, waybills:account:export')")
    @Log(title = "运单信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export/{mode}")
    public void export(HttpServletResponse response, TWayBillInfo tWayBillInfo, @PathVariable Integer mode)
    {
        // 0，运单管理，2，签收管理，3，综合查询，4，运单挂账
        List<TWayBillInfo> list = tWayBillInfoService.selectTWayBillInfoList(tWayBillInfo);
        ExcelUtil<TWayBillInfo> util = new ExcelUtil<TWayBillInfo>(TWayBillInfo.class);
        if(mode == 0) { // 0，运单管理
            util.hideColumn("settlementMethod", "settlementStatus", "settlementPerson", "settlementDate"
                    , "minorSettlementMethod", "minorSettlementStatus", "minorSettlementPerson", "minorSettlementDate"
                    , "signStatus", "signPerson", "signDate", "signRemark"
                    , "cashRefuel", "designateRefuel", "tollFeeCash", "tollFeeEtc", "forfeit", "repairTruckFee"
                    , "serviceStationRepair", "tireFee", "otherFee", "insurancePremium", "vehicleVesselTax", "greatDipperFee"
                    , "gasCylinderFee", "expenseTotal", "profit");
        } else if(mode == 2) { // 2，签收管理
            util.hideColumn("settlementMethod", "settlementStatus", "settlementPerson", "settlementDate"
                    , "minorSettlementMethod", "minorSettlementStatus", "minorSettlementPerson", "minorSettlementDate"
                    , "cashRefuel", "designateRefuel", "tollFeeCash", "tollFeeEtc", "forfeit", "repairTruckFee"
                    , "serviceStationRepair", "tireFee", "otherFee", "insurancePremium", "vehicleVesselTax", "greatDipperFee"
                    , "gasCylinderFee", "expenseTotal", "profit"
                    , "freightPriceMode", "freightPrice", "freightAmount", "handleCost", "freightTotalAmount"
                    , "settlementPriceMode", "settlementPrice", "settlementAmount", "settlementTotalAmount", "wayBillRemark"
                    , "settlementCustomer", "minorFreightAmount", "minorSettlementPriceMode", "minorSettlementPrice"
                    , "minorSettlementAmount", "minorSettlementCustomer", "informationFee", "minorInformationFee");

        } else if(mode == 3) { // 3，综合查询

        } else if(mode == 4) { // 4，运单挂账
            util.hideColumn("signStatus", "signPerson", "signDate", "signRemark");
        }
        util.exportExcel(response, list, "运单信息数据");
    }

    /**
     * 获取运单信息详细信息
     */
    @PreAuthorize("@ss.hasAnyPermi('waybills:waybill:query, waybills:upwardwaybill:query, waybills:downwardwaybill:query, waybills:sign:query, waybills:query:query, waybills:account:query')")
    @GetMapping(value = "/{wayBillId}")
    public AjaxResult getInfo(@PathVariable("wayBillId") Long wayBillId)
    {
        return success(tWayBillInfoService.selectTWayBillInfoByWayBillId(wayBillId));
    }

    /**
     * 新增运单信息
     */
    @PreAuthorize("@ss.hasAnyPermi('waybills:waybill:add, waybills:upwardwaybill:add, waybills:downwardwaybill:add, waybills:sign:add, waybills:query:add')")
    @Log(title = "运单信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TWayBillInfo tWayBillInfo)
    {
        Integer rtn = 0;
        // 校验运单编号唯一
        if (WaybillConstants.NOT_UNIQUE.equals(tWayBillInfoService.checkWayBillNumberUnique(tWayBillInfo)))
        {
            return error("新增回单'" + tWayBillInfo.getWayBillNumber() + "'失败，回单已存在");
        }
        // 更新电话相关信息
        updateMobileAndNumberRelateInfo(tWayBillInfo);
        tWayBillInfo.setCreateBy(getNickName());
        if(StringUtils.isNotNull(tWayBillInfo.getWayBillMark()) && tWayBillInfo.getWayBillMark().equals("1") && StringUtils.isNotNull(tWayBillInfo.getUpwardWayBillNumber())) {
            TWayBillInfo wayBillInfo = new TWayBillInfo();
            wayBillInfo.setWayBillNumber(tWayBillInfo.getUpwardWayBillNumber());
            wayBillInfo.setDownwardWayBillNumber(tWayBillInfo.getWayBillNumber());
            wayBillInfo.setReturnWayBillMark("1");
            rtn = tWayBillInfoService.updateTWayBillInfoByWayBillNumber(wayBillInfo);
            if(rtn < 1) {
                logger.error("TWayBillInfo Upadte Return WayBill Mark error, wayBillNumber = " + wayBillInfo.getWayBillNumber());
            }
            // 删除回单，校验唯一已经删除，此处不需要重复操作
            //tWayBillInfoService.deleteTWayBillInfoByWayBillNumber(tWayBillInfo.getWayBillNumber());
        }

        rtn = tWayBillInfoService.insertTWayBillInfo(tWayBillInfo);
        // 计算，已发车数，已发重量，已发件数，剩余重量，剩余件数
        if((rtn > 0) && StringUtils.isNotEmpty(tWayBillInfo.getTransportPlanNumber())) {
            tTransportPlanService.updateTTransportPlanDespatchWeightPieceByNumber(tWayBillInfo.getTransportPlanNumber());
        }
        return toAjax(rtn);
    }

    /**
     * 修改运单信息
     */
    @PreAuthorize("@ss.hasAnyPermi('waybills:waybill:edit, waybills:upwardwaybill:edit, waybills:downwardwaybill:edit, waybills:sign:edit, waybills:query:edit, waybills:account:edit')")
    @Log(title = "运单信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TWayBillInfo tWayBillInfo)
    {
        Integer rtn = 0;
        // 判断运单状态，已挂账
        TWayBillInfo wayBillInfo = tWayBillInfoService.selectTWayBillInfoByWayBillId(tWayBillInfo.getWayBillId());
        if(StringUtils.isNotNull(wayBillInfo) && wayBillInfo.getPendAccountStatus().equals("已挂账")) {
            return error("当前运单，已挂账，修改失败！");
        }
        // 更新电话相关信息
        updateMobileAndNumberRelateInfo(tWayBillInfo);
        tWayBillInfo.setUpdateBy(getNickName());
        rtn = tWayBillInfoService.updateTWayBillInfo(tWayBillInfo);
        // 计算，已发车数，已发重量，已发件数，剩余重量，剩余件数
        if((rtn > 0) && StringUtils.isNotEmpty(tWayBillInfo.getTransportPlanNumber())) {
            tTransportPlanService.updateTTransportPlanDespatchWeightPieceByNumber(tWayBillInfo.getTransportPlanNumber());
        }
        return toAjax(rtn);
    }

    /**
     * 删除运单信息
     */
    @PreAuthorize("@ss.hasAnyPermi('waybills:waybill:remove, waybills:upwardwaybill:remove, waybills:downwardwaybill:remove, waybills:sign:remove, waybills:query:remove')")
    @Log(title = "运单信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{wayBillIds}")
    public AjaxResult remove(@PathVariable Long[] wayBillIds)
    {
        Integer rtn = 0;
        // 判断运单状态，已签收，已挂账
        for(Long wayBillId : wayBillIds) {
            TWayBillInfo wayBillInfo = tWayBillInfoService.selectTWayBillInfoByWayBillId(wayBillId);
            if(StringUtils.isNotNull(wayBillInfo) && (wayBillInfo.getWayBillStatus().equals("已签收") || wayBillInfo.getPendAccountStatus().equals("已挂账"))) {
                return error("当前运单，已签收/已挂账，删除失败！");
            }
        }

        List<String> transportPlanNumberList = tWayBillInfoService.selectTransportPlanNumberByWayBillIds(wayBillIds);
        rtn = tWayBillInfoService.deleteTWayBillInfoByWayBillIds(wayBillIds);
        // 计算，已发车数，已发重量，已发件数，剩余重量，剩余件数
        if((rtn > 0) && StringUtils.isNotEmpty(transportPlanNumberList)) {
            for (String transportPlanNumber : transportPlanNumberList) {
                //logger.debug("XXX remove " + "transportPlanNumber = " + transportPlanNumber);
                tTransportPlanService.updateTTransportPlanDespatchWeightPieceByNumber(transportPlanNumber);
            }
        }
        return toAjax(rtn);
    }

    /**
     * 计算并修改运单信息
     */
    @PreAuthorize("@ss.hasAnyPermi('waybills:waybill:edit, waybills:upwardwaybill:edit, waybills:downwardwaybill:edit, waybills:sign:edit, waybills:query:edit, waybills:account:edit')")
    @Log(title = "运单信息", businessType = BusinessType.CALCULATE)
    @PutMapping("/calculate")
    public AjaxResult calculate(@RequestBody TWayBillInfo tWayBillInfo)
    {
        tWayBillInfo.setUpdateBy(getNickName());
        return toAjax(tWayBillInfoService.updateTWayBillInfo(calculateAndUpdateTWayBillInfo(tWayBillInfo)));
    }

    /**
     * 更新“发货电话”相关信息，
     * 更新“收货电话”相关信息，
     * 更新“车牌号”相关信息
     */
    private void updateMobileAndNumberRelateInfo(TWayBillInfo tWayBillInfo) {
        TSendReceiveInfo tSendReceiveInfo = new TSendReceiveInfo();
        TVehicleDriverInfo tVehicleDriverInfo = new TVehicleDriverInfo();

        //更新电话，人，地址，流向，
        /* 发货电话不为空，处理 */
        if(!(tWayBillInfo.getSendGoodsMobile() == null || tWayBillInfo.getSendGoodsMobile().isEmpty())) {
            tSendReceiveInfo.setMobile(tWayBillInfo.getSendGoodsMobile());
            TSendReceiveInfo sendReceiveInfo = tSendReceiveInfoService.selectTSendReceiveInfoByMobile(tWayBillInfo.getSendGoodsMobile());
            tSendReceiveInfo.setMobile(tWayBillInfo.getSendGoodsMobile());
            tSendReceiveInfo.setPerson(tWayBillInfo.getSendGoodsPerson());
            tSendReceiveInfo.setAddress(tWayBillInfo.getSendGoodsAddress());
            tSendReceiveInfo.setDirection(tWayBillInfo.getBeginFlowDirection());
            tSendReceiveInfo.setCustomer(tWayBillInfo.getSendGoodsCustomer());

            if (StringUtils.isNull(sendReceiveInfo)) {
                tSendReceiveInfo.setCreateBy(getNickName());
                tSendReceiveInfo.setRemark(null);
                tSendReceiveInfo.setUpdateBy(null);
                tSendReceiveInfo.setUpdateTime(null);
                tSendReceiveInfoService.insertTSendReceiveInfo(tSendReceiveInfo);
            } else {
                tSendReceiveInfo.setSendReceiveId(sendReceiveInfo.getSendReceiveId());
                tSendReceiveInfo.setUpdateBy(getNickName());
                tSendReceiveInfoService.updateTSendReceiveInfo(tSendReceiveInfo);
            }
        } else {
            logger.debug("Send HHH mobile is empty ");
        }
        /* 收货电话不为空，处理 */
        if(!(tWayBillInfo.getReceiveGoodsMobile() == null || tWayBillInfo.getReceiveGoodsMobile().isEmpty())) {
            tSendReceiveInfo.setMobile(tWayBillInfo.getReceiveGoodsMobile());
            TSendReceiveInfo sendReceiveInfo = tSendReceiveInfoService.selectTSendReceiveInfoByMobile(tWayBillInfo.getReceiveGoodsMobile());
            tSendReceiveInfo.setMobile(tWayBillInfo.getReceiveGoodsMobile());
            tSendReceiveInfo.setPerson(tWayBillInfo.getReceiveGoodsPerson());
            tSendReceiveInfo.setAddress(tWayBillInfo.getReceiveGoodsAddress());
            tSendReceiveInfo.setDirection(tWayBillInfo.getEndFlowDirection());
            tSendReceiveInfo.setCustomer(tWayBillInfo.getReceiveGoodsCustomer());
            tSendReceiveInfo.setRemark(tWayBillInfo.getReceiveGoodsRemark());

            if (StringUtils.isNull(sendReceiveInfo)) {
                tSendReceiveInfo.setCreateBy(getNickName());
                tSendReceiveInfo.setUpdateBy(null);
                tSendReceiveInfo.setUpdateTime(null);
                tSendReceiveInfoService.insertTSendReceiveInfo(tSendReceiveInfo);
            } else {
                tSendReceiveInfo.setSendReceiveId(sendReceiveInfo.getSendReceiveId());
                tSendReceiveInfo.setUpdateBy(getNickName());
                tSendReceiveInfoService.updateTSendReceiveInfo(tSendReceiveInfo);
            }
        } else {
            logger.debug("Receive HHH mobile is empty ");
        }
        //更新车牌，司机，电话
        if(!(tWayBillInfo.getVehicleLicenseNumber() == null || tWayBillInfo.getVehicleLicenseNumber().isEmpty())) {
            tVehicleDriverInfo.setVehicleLicenseNumber(tWayBillInfo.getVehicleLicenseNumber());
            List<TVehicleDriverInfo> list = tVehicleDriverInfoService.selectTVehicleDriverInfoByNumber(tVehicleDriverInfo);
            tVehicleDriverInfo.setDriverName(tWayBillInfo.getDriverName());
            tVehicleDriverInfo.setContactMobile(tWayBillInfo.getContactMobile());
            if (list.isEmpty()) {
                tVehicleDriverInfo.setCreateBy(getNickName());
                tVehicleDriverInfo.setUpdateBy(null);
                tVehicleDriverInfoService.insertTVehicleDriverInfo(tVehicleDriverInfo);
            } else {
                tVehicleDriverInfo.setVehicleDriverId(list.get(0).getVehicleDriverId());
                tVehicleDriverInfo.setUpdateBy(getNickName());
                tVehicleDriverInfoService.updateTVehicleDriverInfo(tVehicleDriverInfo);
            }
        } else {
            logger.debug("Vehicle HHH Number is empty ");
        }
    }

    private TWayBillInfo calculateAndUpdateTWayBillInfo(TWayBillInfo tWayBillInfo) {
        double totalWeight = tGoodsInfoService.calculateTotalWeightByWayBillNumber(tWayBillInfo.getWayBillNumber());
        tWayBillInfo.setFreightWeight(totalWeight);
        return tWayBillInfo;
    }

    /**
     * 查询月利润表，关联运单信息
     */
    @PreAuthorize("@ss.hasAnyPermi('waybills:waybill:list, waybills:upwardwaybill:list, waybills:downwardwaybill:list, waybills:sign:list, waybills:query:list, waybills:account:list')")
    @GetMapping("/monthprofitstatistic/{monthProfitBillId}")
    public TableDataInfo monthprofitstatistic(@PathVariable("monthProfitBillId") Long monthProfitBillId, TWayBillInfo tWayBillInfo)
    {
        startPage();
        List<TWayBillInfo> list = tWayBillInfoService.selectTWayBillInfoByMonthProfitBillId(monthProfitBillId, tWayBillInfo);
        return getDataTable(list);
    }

    /**
     * 运单信息，签收
     */
    @PreAuthorize("@ss.hasAnyPermi('waybills:waybill:edit, waybills:upwardwaybill:edit, waybills:downwardwaybill:edit, waybills:sign:edit, waybills:query:edit, waybills:account:edit')")
    @Log(title = "运单信息", businessType = BusinessType.SIGN)
    @PutMapping("/sign/{wayBillIds}")
    public AjaxResult sign(@PathVariable Long[] wayBillIds, @RequestBody TWayBillInfo tWayBillInfo)
    {
        return toAjax(tWayBillInfoService.updateTWayBillInfoSignRelFieldsByWaybillIds(wayBillIds, tWayBillInfo));
    }

    /**
     * 批量新增运单信息，通过出库单ID
     */
    @Log(title = "运单信息", businessType = BusinessType.INSERT)
    @PostMapping("/exitWarehouse/{exitWarehouseIds}")
    public AjaxResult addByExitWarehouseId(@PathVariable Long[] exitWarehouseIds, @RequestBody TWayBillInfo tWayBillInfo)
    {
        Integer rtn = 0, sum = 0;
        Double freightWeight = 0.0, freightPrice = 0.0, freightAmount = 0.0, settlementPrice = 0.0, settlementAmount = 0.0;
        Double informationFee = 0.0, handleCost = 0.0, expenseTotal = 0.0, profit = 0.0;
        tWayBillInfo.setCreateBy(getNickName());
        // 信息费
        if(StringUtils.isNotNull(tWayBillInfo.getInformationFee())) {
            informationFee = tWayBillInfo.getInformationFee();
        } else {
            informationFee = 0.0;
        }
        // 装卸费
        if(StringUtils.isNotNull(tWayBillInfo.getHandleCost())) {
            handleCost = tWayBillInfo.getHandleCost();
        } else {
            handleCost = 0.0;
        }
        for(Long exitWarehouseId : exitWarehouseIds) {
            WExitWarehouseInfo wExitWarehouseInfo = wExitWarehouseInfoService.selectWExitWarehouseInfoByExitWarehouseId(exitWarehouseId);
            tWayBillInfo.setWayBillStatus("运输中");
            tWayBillInfo.setFreightPaymentStatus("未付款");
            tWayBillInfo.setSettlementStatus("未结算");
            tWayBillInfo.setMinorSettlementStatus("未结算");
            tWayBillInfo.setSignStatus("未签收");
            tWayBillInfo.setPendAccountStatus("未挂账");
            tWayBillInfo.setSendGoodsCustomer(wExitWarehouseInfo.getExitWarehouseCustomer());
            tWayBillInfo.setVehicleLicenseNumber(wExitWarehouseInfo.getExitWarehouseVehicle());
            //tWayBillInfo.setVehicleMark("自有车辆");
            tWayBillInfo.setDriverName(wExitWarehouseInfo.getExitWarehouseDriver());
            tWayBillInfo.setContactMobile(wExitWarehouseInfo.getExitWarehouseMobile());
            tWayBillInfo.setGoodsType(wExitWarehouseInfo.getGoodsType());
            if(StringUtils.isNotNull(wExitWarehouseInfo.getWeight())) {
                freightWeight = wExitWarehouseInfo.getWeight();
            } else {
                freightWeight = 0.0;
            }
            tWayBillInfo.setFreightWeight(freightWeight);
            tWayBillInfo.setFreightNumber(wExitWarehouseInfo.getNumberOfPiece());
            // 结算单价
            if(StringUtils.isNotNull(tWayBillInfo.getSettlementPrice())) {
                settlementPrice = tWayBillInfo.getSettlementPrice();
            } else {
                settlementPrice = 0.0;
            }
            // 计算结算
            if(StringUtils.isNotEmpty(tWayBillInfo.getSettlementPriceMode())) {
                if(tWayBillInfo.getSettlementPriceMode().equals("按吨")) {
                    settlementAmount = freightWeight * settlementPrice;
                } else {
                    settlementAmount = settlementPrice;
                }
                settlementAmount = Math.round(settlementAmount * 100.0) / 100.0;
            } else {
                settlementAmount = 0.0;
            }
            tWayBillInfo.setSettlementAmount(settlementAmount);
            tWayBillInfo.setSettlementTotalAmount(settlementAmount);
            // 运费单价
            if (StringUtils.isNotNull(tWayBillInfo.getFreightPrice())) {
                freightPrice = tWayBillInfo.getFreightPrice();
            } else {
                freightPrice = 0.0;
            }
            // 计算运费
            if (StringUtils.isNotEmpty(tWayBillInfo.getFreightPriceMode())) {
                if (tWayBillInfo.getFreightPriceMode().equals("按吨")) {
                    freightAmount = freightWeight * freightPrice;
                } else {
                    freightAmount = freightPrice;
                }
            } else {
                freightAmount = 0.0;
            }
            if(StringUtils.isNotNull(tWayBillInfo.getVehicleMark()) && tWayBillInfo.getVehicleMark().equals("外协车辆")) {
                freightAmount = freightAmount - informationFee - handleCost;
                freightAmount = Math.round(freightAmount * 100.0) / 100.0;
                // 支出总计
                expenseTotal = freightAmount;
            } else {
                freightAmount = 0.0;
                expenseTotal = freightAmount + informationFee;
                expenseTotal = Math.round(expenseTotal * 100.0) / 100.0;
            }
            tWayBillInfo.setFreightAmount(freightAmount);
            tWayBillInfo.setFreightTotalAmount(freightAmount);
            tWayBillInfo.setExpenseTotal(expenseTotal);
            // 计算利润
            profit = Math.round((settlementAmount - expenseTotal) * 100.0) / 100.0;
            tWayBillInfo.setProfit(profit);

            // 运单编号
            TNumberPersistenceInfo tNumberPersistenceInfo = tNumberPersistenceInfoService.getOne(1L);
            tWayBillInfo.setWayBillNumber(tNumberPersistenceInfo.getFormatNumber());
            rtn = tWayBillInfoService.insertTWayBillInfo(tWayBillInfo);
            if(rtn < 1) {
                logger.error("Batch Push WayBill error, exitWarehouseNumber = " + wExitWarehouseInfo.getExitWarehouseNumber());
            }
            if(StringUtils.isNotEmpty(tWayBillInfo.getTransportPlanNumber())) {
                rtn = tTransportPlanService.updateTTransportPlanDespatchWeightPieceByNumber(tWayBillInfo.getTransportPlanNumber());
                if(rtn < 1) {
                    logger.error("Update Transport Plan Remain Weight Piece error, transportPlanNumber = " + tWayBillInfo.getTransportPlanNumber());
                }
            }
            sum++;
        }
        return toAjax(sum);
    }

    /**
     * 批量新增回程运单，通过运单ID
     */
    @PreAuthorize("@ss.hasAnyPermi('waybills:waybill:edit, waybills:upwardwaybill:edit, waybills:downwardwaybill:edit, waybills:sign:edit, waybills:query:edit, waybills:account:edit')")
    @Log(title = "运单信息", businessType = BusinessType.INSERT)
    @PostMapping("/upwardwaybill/{wayBillIds}")
    public AjaxResult addByWayBillId(@PathVariable Long[] wayBillIds, @RequestBody TWayBillInfo tWayBillInfo)
    {
//        logger.debug("addByWayBillId wayBillIds = " + Arrays.toString(wayBillIds));
//        logger.debug("addByWayBillId tWayBillInfo = " + tWayBillInfo);
        Integer rtn = 0, sum = 0;
        //Double freightWeight = 0.0, freightPrice = 0.0, freightAmount = 0.0, settlementPrice = 0.0, settlementAmount = 0.0;
        //Double informationFee = 0.0, expenseTotal = 0.0, profit = 0.0;
        //String wayBillNumber;
        tWayBillInfo.setCreateBy(getNickName());
        List<TWayBillInfo> wayBillInfoList = tWayBillInfoService.selectTWayBillInfoListByWayBillIds(wayBillIds);
        // 校验运单编号唯一
        TWayBillInfo billInfo = new TWayBillInfo();
        for(TWayBillInfo wayBillInfo : wayBillInfoList) {
            billInfo.setWayBillNumber(wayBillInfo.getWayBillNumber() + "回");
            if (WaybillConstants.NOT_UNIQUE.equals(tWayBillInfoService.checkWayBillNumberUnique(billInfo))) {
                return error("新增回单'" + billInfo.getWayBillNumber() + "'失败，回单已存在");
            }
        }
        for(TWayBillInfo wayBillInfo : wayBillInfoList) {
            tWayBillInfo.setWayBillStatus("运输中");
            tWayBillInfo.setFreightPaymentStatus("未付款");
            tWayBillInfo.setSettlementStatus("未结算");
            tWayBillInfo.setMinorSettlementStatus("未结算");
            tWayBillInfo.setSignStatus("未签收");
            tWayBillInfo.setPendAccountStatus("未挂账");
            //tWayBillInfo.setSendGoodsAddress(wayBillInfo.getReceiveGoodsAddress());
            tWayBillInfo.setBeginFlowDirection(wayBillInfo.getEndFlowDirection());
            tWayBillInfo.setVehicleLicenseNumber(wayBillInfo.getVehicleLicenseNumber());
            tWayBillInfo.setVehicleMark(wayBillInfo.getVehicleMark());
            tWayBillInfo.setDriverName(wayBillInfo.getDriverName());
            tWayBillInfo.setContactMobile(wayBillInfo.getContactMobile());

            tWayBillInfo.setWayBillMark("1");
            tWayBillInfo.setUpwardWayBillNumber(wayBillInfo.getWayBillNumber());
            // 运单编号
            //TNumberPersistenceInfo tNumberPersistenceInfo = tNumberPersistenceInfoService.getOne(1L);
            //tWayBillInfo.setWayBillNumber(tNumberPersistenceInfo.getFormatNumber());
            tWayBillInfo.setWayBillNumber(wayBillInfo.getWayBillNumber() + "回");
            // 删除回单
            tWayBillInfoService.deleteTWayBillInfoByWayBillNumber(tWayBillInfo.getWayBillNumber());
            rtn = tWayBillInfoService.insertTWayBillInfo(tWayBillInfo);
            if(rtn > 0) {
                wayBillInfo.setReturnWayBillMark("1");
                wayBillInfo.setDownwardWayBillNumber(tWayBillInfo.getWayBillNumber());
                tWayBillInfoService.updateTWayBillInfoByWayBillNumber(wayBillInfo);
            }
            sum++;
        }
        return toAjax(sum);
    }

    /**
     * 查询运单信息列表，查询，去程，回程运单，一对
     */
    @PreAuthorize("@ss.hasAnyPermi('waybills:waybill:list, waybills:upwardwaybill:list, waybills:downwardwaybill:list, waybills:sign:list, waybills:query:list, waybills:account:list')")
    @GetMapping("/list/ext")
    public TableDataInfo listExt(TWayBillInfo tWayBillInfo)
    {
        String bundleNumber = tWayBillInfo.getBundleNumber();
        if(StringUtils.isNotEmpty(bundleNumber)) {
            tWayBillInfo.setBundleNumber(bundleNumber.replace(",", "|"));
        }

        startPage();
        List<TWayBillInfo> list = tWayBillInfoService.selectTWayBillInfoListExt(tWayBillInfo);
        return getDataTable(list);
    }

    /**
     * 运单信息，挂账
     */
    @PreAuthorize("@ss.hasAnyPermi('waybills:waybill:edit, waybills:upwardwaybill:edit, waybills:downwardwaybill:edit, waybills:sign:edit, waybills:query:edit, waybills:account:edit')")
    @Log(title = "运单信息", businessType = BusinessType.ACCOUNT)
    @PutMapping("/account")
    public AjaxResult account(@RequestBody TWayBillInfo tWayBillInfo)
    {
        Integer rtn = 0;
        tWayBillInfo.setUpdateBy(getNickName());
        rtn = tWayBillInfoService.updateTWayBillInfo(tWayBillInfo);
        // 计算，已发车数，已发重量，已发件数，剩余重量，剩余件数
        if((rtn > 0) && StringUtils.isNotEmpty(tWayBillInfo.getTransportPlanNumber())) {
            tTransportPlanService.updateTTransportPlanDespatchWeightPieceByNumber(tWayBillInfo.getTransportPlanNumber());
        } else {
            logger.error("Update Way Bill account error, wayBillNumber = " + tWayBillInfo.getWayBillNumber());
        }
        return toAjax(rtn);
    }

    /**
     * 删除运单信息，挂账处删除，不进行校验
     */
    @PreAuthorize("@ss.hasAnyPermi('waybills:waybill:remove, waybills:upwardwaybill:remove, waybills:downwardwaybill:remove, waybills:sign:remove, waybills:query:remove')")
    @Log(title = "运单信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/account/{wayBillIds}")
    public AjaxResult erasure(@PathVariable Long[] wayBillIds)
    {
        Integer rtn = 0;
        List<String> transportPlanNumberList = tWayBillInfoService.selectTransportPlanNumberByWayBillIds(wayBillIds);
        rtn = tWayBillInfoService.deleteTWayBillInfoByWayBillIds(wayBillIds);
        // 计算，已发车数，已发重量，已发件数，剩余重量，剩余件数
        if((rtn > 0) && StringUtils.isNotEmpty(transportPlanNumberList)) {
            for (String transportPlanNumber : transportPlanNumberList) {
                tTransportPlanService.updateTTransportPlanDespatchWeightPieceByNumber(transportPlanNumber);
            }
        }
        return toAjax(rtn);
    }

    /**
     * 运单信息，挂账
     */
    @PreAuthorize("@ss.hasAnyPermi('waybills:waybill:edit, waybills:upwardwaybill:edit, waybills:downwardwaybill:edit, waybills:sign:edit, waybills:query:edit, waybills:account:edit')")
    @Log(title = "运单信息", businessType = BusinessType.SETTLEMENT)
    @PutMapping("/settlement")
    public AjaxResult settlement(@RequestBody TWayBillInfo tWayBillInfo)
    {
        Integer rtn = 0;
        tWayBillInfo.setUpdateBy(getNickName());
        rtn = tWayBillInfoService.updateTWayBillInfo(tWayBillInfo);
        // 计算，已发车数，已发重量，已发件数，剩余重量，剩余件数
        if(rtn < 1) {
            logger.error("Update Way Bill settlement error, wayBillNumber = " + tWayBillInfo.getWayBillNumber());
        }
        return toAjax(rtn);
    }

    /**
     * 导出运单信息列表，月利润单，关联运单导出
     */
    @PreAuthorize("@ss.hasAnyPermi('waybills:waybill:export, waybills:upwardwaybill:export, waybills:downwardwaybill:export, waybills:sign:export, waybills:query:export, waybills:account:export')")
    @Log(title = "运单信息", businessType = BusinessType.EXPORT)
    @PostMapping("/exportrelatewaybill/profit/{monthProfitBillId}")
    public void exportrelatewaybillProfit(HttpServletResponse response, TWayBillInfo tWayBillInfo, @PathVariable Long monthProfitBillId)
    {
        List<TWayBillInfo> list = tWayBillInfoService.selectTWayBillInfoByMonthProfitBillId(monthProfitBillId, tWayBillInfo);;
        ExcelUtil<TWayBillInfo> util = new ExcelUtil<TWayBillInfo>(TWayBillInfo.class);
        util.hideColumn("signStatus", "signPerson", "signDate", "signRemark");
        util.exportExcel(response, list, "运单信息数据");
    }

    /**
     * 查询月工资表，关联运单信息
     */
    @PreAuthorize("@ss.hasAnyPermi('waybills:waybill:list, waybills:upwardwaybill:list, waybills:downwardwaybill:list, waybills:sign:list, waybills:query:list, waybills:account:list')")
    @GetMapping("/monthsalarystatistic/{monthSalaryBillId}")
    public TableDataInfo monthsalarystatistic(@PathVariable("monthSalaryBillId") Long monthSalaryBillId, TWayBillInfo tWayBillInfo)
    {
        startPage();
        List<TWayBillInfo> list = tWayBillInfoService.selectTWayBillInfoByMonthSalaryBillId(monthSalaryBillId, tWayBillInfo);
        return getDataTable(list);
    }

    /**
     * 导出运单信息列表，月利润单，关联运单导出
     */
    @PreAuthorize("@ss.hasAnyPermi('waybills:waybill:export, waybills:upwardwaybill:export, waybills:downwardwaybill:export, waybills:sign:export, waybills:query:export, waybills:account:export')")
    @Log(title = "运单信息", businessType = BusinessType.EXPORT)
    @PostMapping("/exportrelatewaybill/salary/{monthSalaryBillId}")
    public void exportrelatewaybillSalary(HttpServletResponse response, TWayBillInfo tWayBillInfo, @PathVariable Long monthSalaryBillId)
    {
        List<TWayBillInfo> list = tWayBillInfoService.selectTWayBillInfoByMonthSalaryBillId(monthSalaryBillId, tWayBillInfo);;
        ExcelUtil<TWayBillInfo> util = new ExcelUtil<TWayBillInfo>(TWayBillInfo.class);
        util.hideColumn("signStatus", "signPerson", "signDate", "signRemark");
        util.exportExcel(response, list, "运单信息数据");
    }
}
